package com.hwadee.property.util;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.util.HashMap;
import java.util.UUID;

@EqualsAndHashCode(callSuper = true)
@Data
@ToString
public class AjaxResult extends HashMap<String, Object> {
    private static final String CODE = "code"; // 状态码
    private static final String MSG = "msg"; // 提示信息
    private static final String DATA = "data"; // 数据
    private static final String REQUEST_ID = "requestId"; // 请求ID

    // 定义标准化的错误码
    public static final int SUCCESS_CODE = 200;
    public static final int ERROR_CODE = 500;
    public static final int VALIDATION_ERROR_CODE = 400;

    // 定义错误信息
    public static final String SUCCESS_MSG = "成功";
    public static final String FAIL_MSG = "失败";
    public static final String SERVER_ERROR_MSG = "服务器异常";

    /**
     * 成功返回
     */
    public static AjaxResult success() {
        return success(null, null);
    }

    /**
     * 成功返回并携带数据
     */
    public static AjaxResult success(Object data) {
        return success(data, null);
    }

    /**
     * 成功返回并携带数据和请求ID
     */
    public static AjaxResult success(Object data, String requestId) {
        AjaxResult result = new AjaxResult();
        result.put(CODE, SUCCESS_CODE);
        result.put(MSG, SUCCESS_MSG);
        result.put(DATA, data);
        if (requestId != null) {
            result.put(REQUEST_ID, requestId);
        }
        return result;
    }

    /**
     * 失败返回
     */
    public static AjaxResult fail() {
        return fail(null, null);
    }

    /**
     * 失败返回并携带自定义消息
     */
    public static AjaxResult fail(String msg) {
        return fail(msg, null);
    }

    /**
     * 失败返回并携带自定义消息和请求ID
     */
    public static AjaxResult fail(String msg, String requestId) {
        AjaxResult result = new AjaxResult();
        result.put(CODE, ERROR_CODE);
        result.put(MSG, msg == null ? FAIL_MSG : msg);
        if (requestId != null) {
            result.put(REQUEST_ID, requestId);
        }
        return result;
    }

    /**
     * 错误返回，通常用于异常处理
     */
    public static AjaxResult error(String msg) {
        return error(ERROR_CODE, msg, null);
    }

    /**
     * 错误返回并携带自定义错误码和消息
     */
    public static AjaxResult error(int code, String msg) {
        return error(code, msg, null);
    }

    /**
     * 错误返回并携带自定义错误码、消息和请求ID
     */
    public static AjaxResult error(int code, String msg, String requestId) {
        AjaxResult result = new AjaxResult();
        result.put(CODE, code);
        result.put(MSG, msg);
        if (requestId == null) {
            requestId = UUID.randomUUID().toString(); // 默认生成一个请求ID
        }
        result.put(REQUEST_ID, requestId);
        return result;
    }
}
